package com.dzu.medium;

import java.util.Arrays;

/**
 * @author ZhaoDong
 * @date 2022/9/23 17:44
 * @description 189. 轮转数组
 * 给你一个数组，将数组中的元素向右轮转 k 个位置，其中 k 是非负数。
 *
 *  
 *
 * 示例 1:
 *
 * 输入: nums = [1,2,3,4,5,6,7], k = 3
 * 输出: [5,6,7,1,2,3,4]
 * 解释:
 * 向右轮转 1 步: [7,1,2,3,4,5,6]
 * 向右轮转 2 步: [6,7,1,2,3,4,5]
 * 向右轮转 3 步: [5,6,7,1,2,3,4]
 * 示例 2:
 *
 * 输入：nums = [-1,-100,3,99], k = 2
 * 输出：[3,99,-1,-100]
 * 解释:
 * 向右轮转 1 步: [99,-1,-100,3]
 * 向右轮转 2 步: [3,99,-1,-100]
 *  
 *
 * 提示：
 *
 * 1 <= nums.length <= 105
 * -231 <= nums[i] <= 231 - 1
 * 0 <= k <= 105
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/rotate-array
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Test189 {

    public static void main(String[] args) {
        int[] arr = new int[]{-1, -100, 3, 99};
        rotate(arr, 2);
        System.out.println(Arrays.toString(arr));
    }

    public static void rotate2(int[] nums, int k) {

        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; ++i) {
            newArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(newArr, 0, nums, 0, n);
    }

    // 1ms
    public static void rotate(int[] nums, int k) {
        int length = nums.length;
        k = k % length;
        int[] arr = new int[length];
        for (int i = 0; i < nums.length; i++) {
            arr[i] = nums[i];
        }

        for (int i = length - k; i < length; i++) {
            nums[Math.abs(length - i - k)] = arr[i];
        }


        for (int i = 0; i < length - k; i++) {
            nums[k + i] = arr[i];
        }
    }


    // 超时
    public static void rotate1(int[] nums, int k) {

        for (int i = 0; i < k; i++) {

            int last = nums[nums.length - 1];
            for (int j = nums.length - 1; j >= 0; j--) {
                if (j == 0) {
                    nums[0] = last;
                    break;
                }
                nums[j] = nums[j - 1];

            }
        }
    }

}
